package com.busionline.wotu.woochenandroid.tools;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.List;

/**
 * 项目名称：joke
 * 类描述：
 * 创建人：woochen123
 * 创建时间：2017/9/7 21:56
 * getFragments()方法需要先add一个fragment才能使用
 */
public class FragmentManagerHelper {
    private int mContainerRes;
    FragmentManager mFragmentManager;

    public FragmentManagerHelper(FragmentManager fragmentManager, int containerRes) {
        mFragmentManager = fragmentManager;
        mContainerRes = containerRes;
    }

    /**
     * 添加fragment
     * @param fragment
     */
    public void addFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.add(mContainerRes,fragment).commit();
    }

    /**
     * 显示fragment
     * desc : 1.需要先add一个fragment
     */
    public void swithFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        //隐藏所有fragment
        List<Fragment> childfragments = mFragmentManager.getFragments();
        for (Fragment childFragment : childfragments) {
            fragmentTransaction.hide(childFragment);
        }
        //存在就直接显示，没有加添加到FragmentManager中
        if (mFragmentManager.getFragments().contains(fragment)) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(mContainerRes, fragment);
        }
        fragmentTransaction.commit();
    }


    /**
     * 切换fragment(避免状态异常)
     * desc : 1.需要先add一个fragment
     */
    public void swithFragmentAllowingStateLoss(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        //隐藏所有fragment
        List<Fragment> childfragments = mFragmentManager.getFragments();
        for (Fragment childFragment : childfragments) {
            fragmentTransaction.hide(childFragment);
        }
        //存在就直接显示，没有加添加到FragmentManager中
        if (mFragmentManager.getFragments().contains(fragment)) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(mContainerRes, fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
    }


    /**
     * replace切换
     * @param fragment
     */
    public void replaceFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(mContainerRes, fragment).commit();
    }

    /**
     * replace切换（避免状态异常）
     */
    public void replaceFragmentAllowingStateLoss(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(mContainerRes, fragment).commitAllowingStateLoss();
    }
}
